package com.hrg.demo.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author shenzq
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "images.param")
public class ImagesConfig {

    /**
     * 图片存储路径
     */
    private String imageBaseDir;
    /**
     * webUrl拦截请求路径
     */
    private String localImages;

    @PostConstruct
    public void validateAndCreateDirectory() {
        if (imageBaseDir == null || imageBaseDir.trim().isEmpty()) {
            throw new IllegalStateException("必须在 application.yml 中配置 'images.param.image-base-dir' 参数");
        }
        log.info("images.param.image-base-dir :{}", imageBaseDir);
        try {
            Path path = Paths.get(imageBaseDir);

            // 验证路径格式
            if (!isValidPath(path)) {
                throw new IllegalStateException("路径格式无效: " + imageBaseDir);
            }

            // 创建文件夹（如果不存在）
            if (!Files.exists(path)) {
                Files.createDirectories(path);
                log.info("✅ 图片存储文件夹不存在，自动创建成功: " + path.toAbsolutePath());
            } else {
                if (!Files.isDirectory(path)) {
                    throw new IllegalStateException("路径已存在但不是文件夹: " + imageBaseDir);
                }
                log.info("✅ 图片存储文件夹已存在: " + path.toAbsolutePath());
            }

            // 验证权限
            if (!Files.isReadable(path) || !Files.isWritable(path)) {
                throw new IllegalStateException("文件夹没有读写权限: " + imageBaseDir);
            }
            log.info("🎉 图片存储路径权限验证通过: " + path.toAbsolutePath());

        } catch (Exception e) {
            throw new IllegalStateException("图片存储路径验证失败: " + e.getMessage(), e);
        }
    }

    private boolean isValidPath(Path path) {
        try {
            path.toAbsolutePath();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
